<script setup>
import { onMounted } from 'vue'
import Todo from './Todo.vue'
import { ref } from 'vue'
import { SendPostRequest } from './lib'

const list = ref([])

let showForm = ref(false)
let newTodo = ref('')

function toggleShowForm() {
  showForm.value = !showForm.value
}

function SendCreateRequest(title, callback) {
  const apiUrl = 'http://127.0.0.1:1900/api/v1/todo/create'

  SendPostRequest(
    apiUrl,
    {
      title: title,
    },
    callback,
  )
}

function addNewTodo() {
  if (newTodo.value.length > 0) {
    SendCreateRequest(newTodo.value, (data) => {
      list.value.push(data['data'])
      newTodo.value = ''
    })
  }
}

onMounted(() => {
  const url = 'http://localhost:1900/api/v1/todo/index'

  fetch(url)
    .then((res) => {
      if (!res.ok) throw new Error(res.status)
      return res.json()
    })
    .then((json) => {
      // console.log(json['data'])
      list.value = json['data']['list']
    })
    .catch((err) => {
      alert(err.message)
    })
})
</script>

<template>
  <h1>待办事项</h1>
  <div><button @click="toggleShowForm">添加 Todo</button></div>
  <div v-if="showForm">
    <input type="text" v-model="newTodo" />
    <button @click="addNewTodo">添加</button>
  </div>
  <ul>
    <Todo v-for="todo in list" :key="todo.id" :title="todo.title" :id="todo.id" />
  </ul>
</template>

<style scoped>
h1 {
  color: green;
  text-align: center;
}

p {
  color: gray;
  text-align: center;
}
</style>
